/*
 * InstructorConnection.cpp
 *
 *  Created on: 30/05/2011
 *      Author: dela
 */

#include "InstructorConnection.h"

#include <map>
#include <iostream>
#include "common/Course.h"
#include "common/Class.h"
#include "Server.h"

using namespace std;

/**
 *
 */
void InstructorConnection::run() {
	char *data;
	while (isWorking()) {
		// Recivo tipo de operación:
		if (socket.receiveData(&data) > 0) {
			switch (*data) {
			case 1:  // Es un login
				doLogin('I');
				break;
			case 2:  // Creación de curso
				createCourse();
				break;
			case 3:  // Obtener lista de cursos
				returnCourses();
				break;
			case 4:  // Creación de clase
				createClass();
				break;
			case 5:  // Obtener lista de clases
				returnClasses();
				break;
			}
			delete[] data;
			data = NULL;
		}
		if ( data != NULL ) {
			delete[] data;
		}
	}
}


/**
 *
 */
bool InstructorConnection::createCourse() {
	char *data;
	int dataSize = 0;
	dataSize = socket.receiveData(&data);
	bool returnValue = false;
	if (dataSize > 0) {
		Course *c = new Course(data);
		Server::getInstance()->getCourses().erase(c->getId());
		Server::getInstance()->getCourses().insert( pair<unsigned int, Course*>(c->getId(), c));
		returnValue = true;
	}
	delete[] data;

	// Respuesta:
	socket.sendData(1, (char*) &returnValue);
	return returnValue;
}


/**
 *
 */
bool InstructorConnection::createClass() {
	char *data;
	int dataSize = 0;
	dataSize = socket.receiveData(&data);
	bool returnValue = false;
	if (dataSize > 0) {
		Class *c = new Class(data);
		Server::getInstance()->getClasses().erase(c->getId());
		Server::getInstance()->getClasses().insert( pair<unsigned int, Class*>(c->getId(), c));
		returnValue = true;
	}
	delete[] data;

	// Respuesta:
	socket.sendData(1, (char*) &returnValue);
	return returnValue;
}
